﻿// 设置权限
var setAuthorize;
// 设置表单数据
var setFormData;
// 获取表单数据
var getFormData;
// 验证数据是否填写完整
var validForm;
var validBusinessData;
// 保存数据
var save;
var saveDraft;
//校验表单
var verifyBill;
//不可编辑
var setFormDisabled;

var isUpdate = false;

var bootstrap = function ($, learun) {
    "use strict";

    var userinfo;

    // 设置权限
    setAuthorize = function (data, isLook) {
        userinfo = learun.clientdata.get(['userinfo']);
        $("#createUsername").val(userinfo.user.realName);
        $('#postname').val(userinfo.user.postNames);
        //报销人
        $("#userid").lrformselect({
            layerUrl: config.webportal_server + 'pages/system/user/selectOnlyForm.html?companyId=' + userinfo.user.companyId + '&access_token=' + config.getToken().access_token,
            layerUrlW: 400,
            layerUrlH: 300,
            dataUrl: config.base_server() + 'users/getNames?access_token=' + config.getToken().access_token,
            select: function (item) {
                $.ajax({
                    url: config.base_server() + 'users/getPostname?keyValue=' + item.value + '&access_token=' + config.getToken().access_token,
                    data: {},
                    type: 'GET',
                    success: function (res) {
                        if (!!res.data) {
                            $('#postname').val(res.data);
                        }
                    }
                });
            }
        }).lrformselectSet(userinfo.user.id);

        $('#gridTable').css("width", $('.lr-form-wrap').width() - 60);

        //加载费用表格
        initGridCost();

        //禁用输入框自动填充
        $("input[type='text']").each(function (index) {
            this.autocomplete = "off";
        });
    };
    //设置表单不可编辑
    setFormDisabled = function (wfType, upload) {
        if (!!wfType && wfType == 100) {
            $('#form').find('input,textarea,select').attr('disabled', 'disabled');
            if (upload != '1') {
                $('#lrUploader_uploadBtn_filesTicket').hide();
                $('#lrUploader_uploadBtn_filesInvoice').hide();
                $('#lrUploader_uploadBtn_filesList').hide();
            }
            $("#userid").unbind();
            $("#destination").unbind();
            $("#btn_reference").hide();
        }
    };
    // 获取表单数据
    getFormData = function () {
        var formData = $('#form').lrGetFormData();
        formData.vehicle = "";
        $("#vehicle").find('input[type="checkbox"]').each(function (r) {
            if ($(this).prop("checked")) {
                if (formData.vehicle == "") {
                    formData.vehicle += $(this).val();
                } else {
                    formData.vehicle += ("," + $(this).val());
                }

            }
        });

        var costData = [];
        var cost = 0;
        var costDataTmp = $('#gridtable_cost').jfGridGet('rowdatas');

        for (var i = 0, l = costDataTmp.length; i < l; i++) {
            if (!!costDataTmp[i]['itemCode']) {
                if (!costDataTmp[i].money) {
                    learun.alert.error('第' + (i + 1) + '行金额非法');
                    return;
                }
                if (!costDataTmp[i].startTime || !costDataTmp[i].endTime) {
                    learun.alert.error('第' + (i + 1) + '行发生时间非法');
                    return;
                }
                costDataTmp[i].sort = i;
                cost += costDataTmp[i].money;
                costData.push(costDataTmp[i]);
            }
        }
        var postData = formData;
        postData.id = parent.processId;
        postData.costList = costData;
        postData.cost = cost;
        return postData;
    };
    // 设置表单数据
    setFormData = function (processId, wfType, checkPermission, upload) {
        if (processId) {
            $('#filesTicket').lrUploader({isView: false});
            $('#filesTicket_demo').on('click', function () {
                previewFile(config.base_server() + "profile/upload/temp/ticket.png");
            });

            $('#filesInvoice').lrUploader({isView: false, processId: processId, isInvoice: 1});
            $('#filesInvoice_demo').on('click', function () {
                previewFile(config.base_server() + "profile/upload/temp/invoice.png");
            });

            $('#filesList').lrUploader({isView: false});
            $('#filesList_demo').on('click', function () {
                previewFile(config.base_server() + "profile/upload/temp/list.png");
            });

            $.lrSetForm(config.base_server() + 'goabroad2s/findByProcessId?processId=' + processId, function (data) {
                console.log(data);
                if (data != null) {
                    isUpdate = true;
                    $('#form').lrSetFormData(data);
                    $("#processCode").html(data.processCode);
                    var destinationStr = data.destinationStr.split('/');
                    $("#destination").citypicker({
                        province: destinationStr[0],
                        city: !!destinationStr[1] ? destinationStr[1] : "",
                        district: !!destinationStr[2] ? destinationStr[2] : ""
                    });
                    $("#vehicle").find('input[type="checkbox"]').each(function (r) {
                        if (data.vehicle.indexOf($(this).val()) >= 0) {
                            $(this).prop("checked", true);
                        }
                    });
                    $('#gridtable_cost').jfGridSet('refreshdata', data.costList);
                    if (data.costList.length < 6) {
                        for (var i = data.costList.length; i < 6; i++) {
                            $('#gridtable_cost').jfGridSet('addRow', {});
                        }
                    }
                } else {
                    $("#destination").citypicker();
                }
                setPbtn(wfType, checkPermission);
            });
        } else {
            setPbtn(wfType, checkPermission);
        }
        setFormDisabled(wfType, upload);
    };
    // 验证数据是否填写完整
    validForm = function (code) {
        if (!$('#form').lrValidform()) {
            return false;
        }
        var startTime = $("#startTime").val();
        var endTime = $("#endTime").val();
        if (endTime < startTime) {
            learun.alert.error("请正确填写日期区间");
            return false;
        }
        if ($('#filesInvoice').find('.lrUploader-input').text() == '') {
            learun.alert.error("请上传【发票】");
            return false;
        }
        if ($('#filesList').find('.lrUploader-input').text() == '') {
            learun.alert.error("请上传【其他资料】");
            return false;
        }
        var costData = [];
        var costDataTmp = $('#gridtable_cost').jfGridGet('rowdatas');
        var hasPlane = false, hasTrain = false; //判断机票火车票
        for (var i = 0, l = costDataTmp.length; i < l; i++) {
            if (!!costDataTmp[i]['itemCode']) {
                if (!costDataTmp[i].money) {
                    learun.alert.error('第' + (i + 1) + '行金额非法');
                    return;
                }
                if (!costDataTmp[i].startTime || !costDataTmp[i].endTime) {
                    learun.alert.error('第' + (i + 1) + '行发生时间非法');
                    return;
                }
                if (costDataTmp[i].startTime > costDataTmp[i].endTime) {
                    learun.alert.error("第" + (i + 1) + "行日期区间非法");
                    return;
                }
                if (costDataTmp[i].days < 0) {
                    learun.alert.error("第" + (i + 1) + "行天数非法");
                    return;
                }
                if (costDataTmp[i].money < 0) {
                    learun.alert.error("第" + (i + 1) + "行金额非法");
                    return;
                }
                if (costDataTmp[i]['itemCode'] == 2) { //含有机票
                    hasPlane = true;
                }
                if (costDataTmp[i]['itemCode'] == 3) { //含有火车票
                    hasTrain = true;
                }
                costData.push(costDataTmp[i]);
            }
        }
        var cbPlane = $('#vehicle1').is(':checked');
        if (hasPlane == true && cbPlane == false) {
            learun.alert.error('检测到费用明细包含机票费，交通方式请勾选飞机');
            return false;
        }
        var cbTrain = $('#vehicle2').is(':checked');
        if (hasTrain == true && cbTrain == false) {
            learun.alert.error('检测到费用明细包含火车票费，交通方式请勾选火车');
            return false;
        }
        if (costData.length == 0) {
            learun.alert.error('费用明细信息不全,请检查！');
            return false;
        }

        return true;
    };
    validBusinessData = function () {
        return true;
    }

    // 校验调用函数
    verifyBill = function (processId, callBack, i) {
        var keyValue = "";

        if (isUpdate) {
            keyValue = processId;
        }

        var formData = $('#form').lrGetFormData();
        formData.vehicle = "";
        $("#vehicle").find('input[type="checkbox"]').each(function (r) {
            if ($(this).prop("checked")) {
                if (formData.vehicle == "") {
                    formData.vehicle += $(this).val();
                } else {
                    formData.vehicle += ("," + $(this).val());
                }

            }
        });

        var costData = [];
        var costDataTmp = $('#gridtable_cost').jfGridGet('rowdatas');

        if (costDataTmp.length == 0) {
            learun.alert.error('费用清单信息不全,请检查！');
            return false;
        }
        var isPlane = false;
        for (var i = 0, l = costDataTmp.length; i < l; i++) {
            if (!!costDataTmp[i]['itemCode']) {
                if (!costDataTmp[i].money) {
                    learun.alert.error('第' + (i + 1) + '行金额非法');
                    return;
                }
                if (!costDataTmp[i].startTime || !costDataTmp[i].endTime) {
                    learun.alert.error('第' + (i + 1) + '行发生时间非法');
                    return;
                }
                if (costDataTmp[i].startTime > costDataTmp[i].endTime) {
                    learun.alert.error("第" + (i + 1) + "行日期区间非法");
                    return;
                }
                if (costDataTmp[i].days < 0) {
                    learun.alert.error("第" + (i + 1) + "行天数非法");
                    return;
                }
                if (costDataTmp[i].money < 0) {
                    learun.alert.error("第" + (i + 1) + "行金额非法");
                    return;
                }
                if (costDataTmp[i]['itemCode'] == 2) {
                    isPlane = true;
                }
                costDataTmp[i].sort = i;
                costData.push(costDataTmp[i]);
            }
        }
        //机票报销需要机票申请说明
        if (isPlane == true) {
            if ($('#filesTicket').find('.lrUploader-input').text() == '') {
                learun.alert.error("请上传【机票申请说明文件】");
                return false;
            }
        }
        var postData = formData;
        postData.id = parent.processId;
        postData.costList = costData

        $.lrSaveFormRule(config.base_server() + 'goabroad2s/verifyBill?keyValue=' + keyValue + '&access_token=' + config.getToken().access_token, JSON.stringify(postData), function (res) {
            if (res.resp_code != 200) {
                $("#errorMsg").show();
                var html = "<div class=\"alert alert-danger\" role=\"alert\">\n" +
                    "            <p>提示：</p>\n" +
                    "            <p>" + res.resp_msg + "</p>\n" +
                    "        </div>"
                $("#gridtable_cost").css("border", "1px solid red;");
                $("#errorMsg").html(html);
            } else {
                $("#errorMsg").hide();
                var html = "<div class=\"alert alert-danger\" role=\"alert\">\n" +
                    "        </div>"
                $("#gridtable_cost").css("border", "1px solid #ddd;");
                $("#errorMsg").html(html);

                // 保存成功后才回调
                if (!!callBack) {
                    callBack(res, i);
                }
            }
        });
    };

    // 保存调用函数
    save = function (processId, force, callBack, i) {
        var keyValue = "";

        if (isUpdate) {
            keyValue = processId;
        }

        var formData = $('#form').lrGetFormData();
        formData.vehicle = "";
        $("#vehicle").find('input[type="checkbox"]').each(function (r) {
            if ($(this).prop("checked")) {
                if (formData.vehicle == "") {
                    formData.vehicle += $(this).val();
                } else {
                    formData.vehicle += ("," + $(this).val());
                }

            }
        });

        var costData = [];
        var costDataTmp = $('#gridtable_cost').jfGridGet('rowdatas');

        if (costDataTmp.length == 0) {
            learun.alert.error('费用清单信息不全,请检查！');
            return false;
        }
        var isPlane = false;
        for (var i = 0, l = costDataTmp.length; i < l; i++) {
            if (!!costDataTmp[i]['itemCode']) {
                if (!costDataTmp[i].money) {
                    learun.alert.error('第' + (i + 1) + '行金额非法');
                    return;
                }
                if (!costDataTmp[i].startTime || !costDataTmp[i].endTime) {
                    learun.alert.error('第' + (i + 1) + '行发生时间非法');
                    return;
                }
                if (costDataTmp[i]['itemCode'] == 2) {
                    isPlane = true;
                }
                costDataTmp[i].sort = i;
                costData.push(costDataTmp[i]);
            }
        }
        //机票报销需要机票申请说明
        if (isPlane == true) {
            if ($('#filesTicket').find('.lrUploader-input').text() == '') {
                learun.alert.error("请上传【机票申请说明文件】");
                return false;
            }
        }
        var postData = formData;
        postData.id = parent.processId;
        postData.costList = costData;

        $.lrSaveFormRule(config.base_server() + 'goabroad2s/saveOrUpdate?keyValue=' + keyValue + '&force=' + force + '&access_token=' + config.getToken().access_token, JSON.stringify(postData), function (res) {
            if (res.resp_code != 200) {
                $("#errorMsg").show();
                var html = "<div class=\"alert alert-danger\" role=\"alert\">\n" +
                    "            <p>提示：</p>\n" +
                    "            <p>" + res.resp_msg + "</p>\n" +
                    "        </div>"
                $("#gridtable_cost").css("border", "1px solid red;");
                $("#errorMsg").html(html);
            } else {
                $("#errorMsg").hide();
                var html = "<div class=\"alert alert-danger\" role=\"alert\">\n" +
                    "        </div>"
                $("#gridtable_cost").css("border", "1px solid #ddd;");
                $("#errorMsg").html(html);

                // 保存成功后才回调
                if (!!callBack) {
                    callBack(res, i);
                }
            }
        });
    };

    // 保存调用函数
    saveDraft = function (processId, force, callBack, i) {
        var keyValue = "";

        if (isUpdate) {
            keyValue = processId;
        }

        var formData = $('#form').lrGetFormData();
        formData.vehicle = "";
        $("#vehicle").find('input[type="checkbox"]').each(function (r) {
            if ($(this).prop("checked")) {
                if (formData.vehicle == "") {
                    formData.vehicle += $(this).val();
                } else {
                    formData.vehicle += ("," + $(this).val());
                }

            }
        });

        var costData = [];
        var costDataTmp = $('#gridtable_cost').jfGridGet('rowdatas');

        for (var i = 0, l = costDataTmp.length; i < l; i++) {
            if (!!costDataTmp[i]['itemCode']) {

                costDataTmp[i].sort = i;
                costData.push(costDataTmp[i]);
            }
        }
        var postData = formData;
        postData.id = parent.processId;
        postData.costList = costData

        $.lrSaveFormRule(config.base_server() + 'goabroad2s/saveOrUpdate?keyValue=' + keyValue + '&force=' + force + '&access_token=' + config.getToken().access_token, JSON.stringify(postData), function (res) {
            if (res.resp_code != 200) {
                $("#errorMsg").show();
                var html = "<div class=\"alert alert-danger\" role=\"alert\">\n" +
                    "            <p>提示：</p>\n" +
                    "            <p>" + res.resp_msg + "</p>\n" +
                    "        </div>"
                $("#gridtable_cost").css("border", "1px solid red;");
                $("#errorMsg").html(html);
            } else {
                $("#errorMsg").hide();
                var html = "<div class=\"alert alert-danger\" role=\"alert\">\n" +
                    "        </div>"
                $("#gridtable_cost").css("border", "1px solid #ddd;");
                $("#errorMsg").html(html);

                // 保存成功后才回调
                if (!!callBack) {
                    callBack(res, i);
                }
            }
        });
    };


    // 设置父级窗口的按钮
    function setPbtn(wfType, checkPermission) {
        if (!!wfType && wfType == 100 && checkPermission == true) { //审核
            // $('#lr-layout-panel-right', window.parent.document).hide();
            $('#verifyBill', window.parent.document).hide();
            $('#flow-force', window.parent.document).show();
            $('#flow-projectinfo', window.parent.document).show();
        } else if (!!wfType && wfType == 100 && checkPermission == false) { //查看
            $('#lr-layout-panel-right', window.parent.document).empty();
        } else {
            $('#release', window.parent.document).text('提交申请');
            // $('.lr-form-item-title', window.parent.document).text('备注');
            //$('#savedraft', window.parent.document).hide();
            $('#flow-force', window.parent.document).show();
            $('#verifyBill', window.parent.document).show();
            $('#flow-projectinfo', window.parent.document).hide();
            $('#sign', window.parent.document).hide();
            $('#flow-title input', window.parent.document).val("探亲费用报销");
            $('#flow-title input', window.parent.document).attr("readonly", "readonly");
            //$('#print', window.parent.document).hide();
        }
    }

    //加载子表格
    function initGridCost() {
        $('#gridtable_cost').jfGrid({
            headData: [
                {
                    label: '事项', name: 'itemCode', width: 120, align: 'center',
                    edit: {
                        type: 'select',
                        change: function (data, num, selectrow) {// 行数据和行号
                            if (!data.startTime) {
                                data.startTime = $("#startTime").val();
                            }
                            if (!data.endTime) {
                                data.endTime = $("#endTime").val();
                            }
                            data.persons = 1;
                            if (data.itemCode == 1 || data.itemCode == 4 || data.itemCode == 5) {
                                var diff = DateDiff(data.startTime, data.endTime);
                                data.days = (diff > 0 ? diff : 1);
                            } else {
                                data.days = 1;
                            }
                            if(data.itemCode == 99) {
                                data.persons = 1;
                            }

                            $('#gridtable_cost').jfGridSet('updateRow', num);


                            var formData = $('#form').lrGetFormData();
                            //伙食补助
                            if (data.itemCode == 4) {
                                $.ajax({
                                    url: config.base_server() + 'stdmealAllowances/getMoney?access_token=' + config.getToken().access_token,
                                    data: {
                                        userId: formData.userid,
                                        persons: data.persons,
                                        destination: formData.destination,
                                        startTime: formData.startTime,
                                        endTime: formData.endTime
                                    },
                                    type: 'GET',
                                    success: function (res) {
                                        if (!!res.data) {
                                            data.money = res.data;
                                            data.price = (res.data / data.persons) / data.days;
                                            $('#gridtable_cost').jfGridSet('updateRow', num);
                                        }
                                    }
                                });
                            } else if (data.itemCode == 5) { //市内交通补助
                                $.ajax({
                                    url: config.base_server() + 'stdtrafficAllowances/getMoney?access_token=' + config.getToken().access_token,
                                    data: {
                                        userId: formData.userid,
                                        persons: data.persons,
                                        destination: formData.destination,
                                        startTime: formData.startTime,
                                        endTime: formData.endTime
                                    },
                                    type: 'GET',
                                    success: function (res) {
                                        if (!!res.data) {
                                            data.money = res.data;
                                            data.price = (res.data / data.persons) / data.days;
                                            $('#gridtable_cost').jfGridSet('updateRow', num);
                                        }
                                    }
                                });
                            }

                        },
                        op: {// 下拉框设置参数 和 lrselect一致
                            data: [
                                {'id': '', 'text': ''},
                                {'id': '1', 'text': '住宿费'},
                                {'id': '2', 'text': '机票费'},
                                {'id': '3', 'text': '火车票'},
                                {'id': '4', 'text': '伙食补助'},
                                {'id': '5', 'text': '市内交通补助'},
                                {'id': '99', 'text': '其他费'}
                            ]
                        }
                    }
                },
                {
                    label: '单价', name: 'price', width: 90, align: 'center',
                    formatter: function (cellvalue) {
                        return $.formatMoney(cellvalue, 2);
                    },
                    edit: {
                        type: 'number',
                        init: function (data, $edit) {// 在点击单元格的时候触发，可以用来初始化输入控件，行数据和控件对象
                        },
                        change: function (data, num) {// 行数据和行号
                            if (!!data.days) {
                                data.money = data.price * data.days;
                                $('#gridtable_cost').jfGridSet('updateRow', num);
                            }
                        }
                    }
                },
                {
                    label: '天数', name: 'days', width: 60, align: 'center',
                    edit: {
                        type: 'number',
                        init: function (data, $edit) {// 在点击单元格的时候触发，可以用来初始化输入控件，行数据和控件对象
                        },
                        change: function (data, num) {// 行数据和行号
                            if (!!data.price) {
                                data.money = data.price * data.days;
                                $('#gridtable_cost').jfGridSet('updateRow', num);
                            }
                        }
                    }
                },
                {
                    label: '金额', name: 'money', width: 100, align: 'center', statistics: true,
                    formatter: function (cellvalue) {
                        return $.formatMoney(cellvalue, 2);
                    },
                    edit: {
                        type: 'number',
                        init: function (data, $edit) {// 在点击单元格的时候触发，可以用来初始化输入控件，行数据和控件对象
                        },
                        change: function (data, num) {// 行数据和行号
                            if (!!data.days) {
                                data.price = (data.money / data.days);
                                $('#gridtable_cost').jfGridSet('updateRow', num);
                            }
                        }
                    }
                },
                {
                    label: '发生时间', name: 'startTime', width: 120, align: 'center',
                    edit: {
                        type: 'datatime',
                        dateformat: '0',       // 0:yyyy-MM-dd;1:yyyy-MM-dd HH:mm,格式
                        init: function (data, $edit) {// 在点击单元格的时候触发，可以用来初始化输入控件，行数据和控件对象
                        },
                        change: function (data, num) {// 行数据和行号

                        }
                    }
                },
                {
                    label: '结束时间', name: 'endTime', width: 120, align: 'center',
                    edit: {
                        type: 'datatime',
                        dateformat: '0',       // 0:yyyy-MM-dd;1:yyyy-MM-dd HH:mm,格式
                        init: function (data, $edit) {// 在点击单元格的时候触发，可以用来初始化输入控件，行数据和控件对象

                        },
                        change: function (data, num) {// 行数据和行号
                        }
                    }
                },
                {
                    label: '费用说明', name: 'remark', width: 100, align: 'left',
                    edit: {
                        type: 'input',
                    }
                }
            ],
            isEdit: true,
            isMultiselect: true,
            // onAddRow: function (row, rows) {//行数据和所有行数据
            //
            // },
            // onMinusRow: function (row, rows) {//行数据和所有行数据
            //
            // },
            // beforeMinusRow: function (row) {// 行数据 返回false 则不许被删除
            //     return true;
            // }
        });
        $('#gridtable_cost').jfGridSet('addRow', {});
        $('#gridtable_cost').jfGridSet('addRow', {});
        $('#gridtable_cost').jfGridSet('addRow', {});
        $('#gridtable_cost').jfGridSet('addRow', {});
        $('#gridtable_cost').jfGridSet('addRow', {});
        $('#gridtable_cost').jfGridSet('addRow', {});
    }

    //文件预览
    function previewFile(url) {
        learun.layerForm({
            id: 'PreviewUrl',
            title: '文件预览',
            url: config.webportal_server + 'pages/utility/previewUrl.html?url=' + url + '&access_token=' + config.getToken().access_token,
            width: 700,
            height: 850,
            btn: null
        });
    }


}

//计算时间差
function DateDiff(sDate, eDate) { //sDate和eDate是yyyy-MM-dd格式
    var date1 = new Date(sDate + ":00:00");
    var date2 = new Date(eDate + ":00:00");
    var date3 = date2.getTime() - date1.getTime();
    var days = Math.floor(date3 / (24 * 3600 * 1000));
    if (days == 0) {
        days = 1;
    } else {
        days += 1;
    }
    return days;
}

